package com.campus.service.impl;

import com.campus.constant.MessageConstant;
import com.campus.constant.StatusConstant;
import com.campus.exception.DeletionNotAllowedException;
import com.campus.exception.ResourceNotFoundException;
import com.campus.exception.UpdateNotAllowedException;
import com.campus.mapper.BusMapper;
import com.campus.pojo.dto.BusDTO;
import com.campus.pojo.dto.BusPageQueryDTO;
import com.campus.pojo.entity.Bus;
import com.campus.pojo.vo.BusVO;
import com.campus.result.PageResult;
import com.campus.service.BusService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.List;

@Service
public class BusServiceImpl implements BusService {
    @Autowired
    private BusMapper busMapper;
    @Override
    public PageResult<BusVO> pageQuery(BusPageQueryDTO busPageQueryDTO) {
        // 1.设置分页参数
        PageHelper.startPage(busPageQueryDTO.getCurrentPage(), busPageQueryDTO.getPageSize());

        // 2.执行分页查询
        Page<BusVO> page = busMapper.pageQuery(busPageQueryDTO);

        // 3.返回结果
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public void save(BusDTO busDTO) {
        //1.构建entity对象-bus
        Bus bus = new Bus();
        BeanUtils.copyProperties(busDTO, bus);

        //2.调用mapper方法
        busMapper.insert(bus);


    }

    @Override
    public void deleteByIds(List<Long> ids) {
        //1.检查有没有运营中的班车 运营中不允许删除 这里直接传入集合查询再返回集合再遍历其实最好
        for (Long id : ids) {
            Bus bus = busMapper.selectById(id);
            if (bus.getStatus() == StatusConstant.BUS_STATUS_OPERATION) {
                throw new DeletionNotAllowedException(MessageConstant.BUS_STATUS_OPERATION_DELETE);
            }
        }

        //2.调用mapper方法
        busMapper.deleteByIds(ids);
    }

    @Override
    public BusVO getById(Long id) {
        return busMapper.getById(id);
    }

    @Override
    public void update(BusDTO busDTO) {
        //1.检查是否有id
        if (busDTO.getId() == null) {
            throw new ResourceNotFoundException(MessageConstant.BUS_NOT_FOUND);
        }

        //2.构建entity对象-bus
        Bus bus = new Bus();
        BeanUtils.copyProperties(busDTO, bus);

        //3.调用mapper方法
        busMapper.update(bus);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        //1.检查该班车是否存在
        Bus bus = busMapper.selectById(id);
        if (bus == null) {
            //不存在
            throw new ResourceNotFoundException(MessageConstant.BUS_NOT_FOUND);
        }

        //2.创建一个新的bus对象 只赋值id 和 status 减少sql复制度
        bus = Bus.builder()
                .id(id)
                .status(status)
                .build();


        //3.调用mapper方法 复用update方法
        busMapper.update(bus);

    }
}
